#include "sphere.hpp"

#include <iostream>
using namespace std;

bool Sphere::Intersect(Ray& intersectRay, double& t)
{
	Vector3D distance=position-intersectRay.startPoint;
	double sqrLength=distance&distance; // lengthRTSC2 = length of the ray from the ray's origin to the sphere's center squared
	double closestApproach = distance & intersectRay.direction;
	
	if (closestApproach <= 0) return false; // the intersection is behind the ray
	
	// D=halfCord2 = the distance squared from the closest approach of the ray to a perpendicular to the ray through the center of the sphere to the place where the ray actually intersects the sphere
	
	double D = (radius*radius) - sqrLength + (closestApproach*closestApproach); 
	
	if (D<0) return false;

	t = closestApproach-sqrt(D);	

	return t > Defined::GeomThreshold;
	// halfCord=D   !!!! 

}

Color Sphere::Trace(Ray& viewRay,Point3D lightPos,double& dist)
{
	
	// calculate the location of the intersection between the sphere and the ray. 
	Vector3D intersection=viewRay.startPoint + dist*viewRay.direction; 

    // calculate the normal of the sphere at the point of interesction, for using later
	normalVect = (intersection-position)*((double)(1.0/double(radius)));   

    // calculate direction from the intersection to light
	Vector3D lightDirection = normalize(lightPos-intersection);   
 
 	double lightCoef=lightDirection & normalVect; //AKA cos   
	
	if (lightCoef<Defined::EPS) lightCoef=0;
	
	if (objTex!=NULL)
		objTex->ApplyTexture(objMat.objectColor, intersection);

	Color tColor = objMat.objectColor*lightCoef;
	return tColor;
}
Vector3D Sphere::GetNormalVect() 
{
//	cout << "Sphere NormVect. X="<<normalVect.x<<"Y= "<<normalVect.y<<"Z="<<normalVect.z<<endl;
	return normalize(normalVect);
}
